package net.danielpaz.pucc.poo.trabalho.model;

/**
 * Classe para manipular dados de objetos da classe Motorista no banco de dados
 * @author Rodolfo
 * @date 14/06/2014
 *
 */


import java.sql.*;

public class MotoristaDAO {
	
	public Motorista mot;
	public Conexao bd;
	private PreparedStatement statement;
	private ResultSet resultSet;
	private String men, sql;
	public static final byte INCLUSAO = 1;
	public static final byte ALTERACAO = 2;
	public static final byte EXCLUSAO = 3;

	public MotoristaDAO() {
		bd = new Conexao();
		mot = new Motorista();
		bd.getConnection();
	}

	
	public Motorista localizar(int id) {
		
		sql = "SELECT * FROM MOTORISTA WHERE ID_FUNCIONARIO = ?";
			
		try {
		
			statement = bd.connection.prepareStatement(sql);
			statement.setInt(1, id);
			resultSet = statement.executeQuery();
		
			while (resultSet.next()) {
				mot.setNumCNH(resultSet.getString(1));
				mot.setCategoria(resultSet.getString(2));
				mot.setId_funcionario(Integer.parseInt(resultSet.getString(3)));
			}
			
			return mot;
		}
		catch (Exception erro) {
				erro.printStackTrace();
				System.out.println(erro.getMessage());
				return null;
		}	
	}
	
	
	public String atualizar(int operacao) {
        men = "Operacao realizada com sucesso!";
        try {
            if (operacao==INCLUSAO) {
        		sql = "insert into motorista values (?,?,?)";
        		statement = bd.connection.prepareStatement(sql);
        		statement.setString(1, "" + mot.getNumCNH());
        		statement.setString(2, "" + mot.getCategoria());
        		statement.setString(3, "" + mot.getId_funcionario());

            } else if (operacao==ALTERACAO) {
            	
            	sql = "update MOTORISTA mot "
            				+ " set mot.numcnh = ?, "
			  			  	+ " mot.categoria = ? "
			  			  	+ " where mot.id_funcionario = ?";
            	
            	System.out.println(sql);
            	statement = bd.connection.prepareStatement(sql);
            	statement.setString(1, "" + mot.getNumCNH());
            	statement.setString(2, "" + mot.getCategoria());
            	statement.setString(3, "" + mot.getId_funcionario());
            	
            } else if (operacao==EXCLUSAO) {
            	sql = "delete from motorista where id_funcionario = ?";            	
            	statement = bd.connection.prepareStatement(sql);
            	statement.setString(1, "" + mot.getId_funcionario());
            }
            
        
            if (statement.executeUpdate() == 0)
                    men = "Falha na operacao!";
            } catch (SQLException erro) {
                men = "Falha na operacao " + erro.toString();
            }
            return men;
        
    }
}